package com.tensquare.article.controller;

import com.tensquare.article.pojo.Comment;
import com.tensquare.article.service.CommentService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private RedisTemplate redisTemplate;


    // GET /comment 查询所有评论
    @GetMapping
    public Result findAll(){
        List<Comment> commentList=commentService.findAll();
        return new Result(true,"查询成功", StatusCode.OK,commentList);
    }


    //GET /comment/{commentId} 根据评论id查询评论数据
    @GetMapping("/{commentId}")
    public Result findById(@PathVariable String commentId){
        Comment comment=commentService.findById(commentId);
        return new Result(true,"查询成功", StatusCode.OK,comment);
    }

    //POST /comment 新增评论
    @PostMapping
    public Result save(@RequestBody Comment comment){
        commentService.save(comment);
        return new Result(true,"添加成功", StatusCode.OK);
    }

    //PUT /comment/{commentId}  根据id修改评论
    @PutMapping("/{commentId}")
    public Result updateById(@PathVariable String commentId,@RequestBody Comment comment){
        comment.set_id(commentId);
        commentService.updateById(comment);
        return new Result(true,"修改成功",StatusCode.OK);
    }


    //DELETE /comment/{commentId} 删除评论
    @DeleteMapping("/{commentId}")
    public Result deleteById(@PathVariable String commentId){
        commentService.deleteById(commentId);
        return new Result(true,"删除成功",StatusCode.OK);
    }


    //GET /comment/article/{articleId}  根据文章ID查询评论
    @GetMapping("/article/{articleId}")
    public Result findByArticleId(@PathVariable String articleId){
        List<Comment> commentList=commentService.findByArticleId(articleId);
        return new Result(true,"查询成功", StatusCode.OK,commentList);
    }

    //PUT /comment/thumbup/{commentId}  点赞
    @PutMapping("/thumbup/{commentId}")
    public Result thump(@PathVariable String commentId){
        //将用户id与评论id保存到Redis中
        String userid="";
        Object flag = redisTemplate.opsForValue().get("thumbup_" + userid + "_" + commentId);
        if(flag==null){
            commentService.thump(commentId);
            redisTemplate.opsForValue().set("thumbup_" + userid + "_" + commentId,1);
            return new Result(true,"点赞成功",StatusCode.OK);
        }

        return new Result(false,"重复点赞",StatusCode.REPERROR);
    }

}
